import 'dart:collection';
import 'dart:convert';

import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_shipper/FandCar/VehicleSourceDetails.dart';
import 'package:url_launcher/url_launcher.dart';

import '../AppConfig/CityLIstData.dart';
import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../AppConfig/ShowDialog.dart';
import '../AppConfig/StringEncapsulation.dart';
import '../http/NoLoadingPostApi.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'SelectSourceOfGoods.dart';
import 'package:platform/platform.dart';

class EmptyCarList extends StatefulWidget {
  const EmptyCarList({super.key});

  @override
  State<EmptyCarList> createState() => _EmptyCarListState();
}

class _EmptyCarListState extends State<EmptyCarList> {
  int selectedDisIndex = -1;
  String selectedProvince = "";
  String selectedCity = "";
  String selectedDistrict = "";
  String currentLevel = "province"; // 初始显示省份
  List startNameList=[];
  List endNameList=[];
  Map sourceDetailsMap={};
  int startHidden=1;
  int endHidden =1;
  int startCheck=1;
  int endCheck=1;
  int addressType=1;
  List isChooseList=[];
  int typeHidden=1;
  List startCodeList=[];
  List endCodeList=[];
  List historyList=['苏州',"无锡","黑龙江"];
  List<String> lengthList = [
    "1.8米", "2.7米", "3.8米", "4.2米", "5米", "6.2米", "6.8米", "7.7米", "8.2米", "8.7米", "9.6米",
    "11.7米", "12.5米", "13米", "13.7米", "15米", "16米", "17.5米"
  ];
  List<String> carTypeList = [
    "平板", "高栏", "厢式", "集装箱", "自卸", "冷藏", "保温",
    "高低板", "面包车", "棉被车", "爬梯车", "飞翼车", "依维柯"
  ];
  List chooseLengthList=[];
  List chooseCarTypeList=[];
  List driverTypeList=['三证齐全','五证齐全'];
  List chooseTypeList=[];
  List dataList=[];
  List chooseStartList=[];
  List chooseEndList=[];
  List cardTypeList=[];
  bool isLoading =false;
  int pageNum=1;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getEmptyCarListAction();
  }

  getEmptyCarListAction() async {
    NoLoadingApiManager.postData(
      context,
      'api/goods/idle/vehicle/page',
      {
        "current": pageNum,
        "size": 20,

      },
          (responseData) {
          setState(() {
            dataList =responseData['data']['records'];
          });
      },
    );
  }



  getNewEmptyCarListAction()async{

    NoLoadingApiManager.postData(
      context,
      'api/goods/idle/vehicle/page',
      {
        "current": pageNum,
        "size": 20,
        "loadPlaceCodeList": startCodeList,
        "unloadPlaceCodeList": endCodeList,
        "vehicleLengthList": chooseLengthList,
        "vehicleModelList": chooseTypeList,
      },
          (responseData) {
        setState(() {
          dataList =responseData['data']['records'];
        });
      },
    );
  }
  _makePhoneCall(String phoneNumber) async {
    if (LocalPlatform().isAndroid) {
      var status = await Permission.phone.status;
      if (status.isGranted) {
        // 权限已被授予
        // callPhone();
        final AndroidIntent intent = AndroidIntent(
          action: 'android.intent.action.CALL',
          data: Uri.encodeFull('tel:$phoneNumber'),
        );
        await intent.launch();
      } else if (status.isDenied) {
        // 权限被拒绝，但用户可以再次授权
        showCallPhoneFirstDialog(context);
        status = await Permission.phone.request();
        if (status.isGranted) {
          // 用户同意了权限
          // callPhone();
          final AndroidIntent intent = AndroidIntent(
            action: 'android.intent.action.CALL',
            data: Uri.encodeFull('tel:$phoneNumber'),
          );
          await intent.launch();
        } else {
          showCallPhoneDialog(context);
          // 用户拒绝权限，无法发起电话
          // 可以在此处展示信息提示用户需要权限
        }
      } else if (status.isPermanentlyDenied) {
        // 权限被永久拒绝，需要用户手动开启权限
        showCallPhoneDialog(context);
      }

    }else{
      final url =Uri.parse('tel:$phoneNumber');
      if (await canLaunchUrl(url)) {
        await launchUrl(url);
      } else {
        throw '无法拨打电话：$url';
      }
    }
  }
  void _onRefresh(){
    getEmptyCarListAction();
  }
  Future _onLoadfresh() async{
    if(dataList.length > 20*pageNum-1){
      pageNum++;
      getNewEmptyCarListAction();
    }

  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Container(

      child: ListView(
        children: [
          SizedBox(height: 1.h,),
          Container(
            color: Colors.white,
            height: 30.h,
            child:   Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  width: screenSize.width/3,
                  child:   BrnIconButton(
                      name: startNameList.length==1?startNameList.join(','): startNameList.length>1?startNameList[1]+",...":'装货地',
                      style: TextStyle(color:startHidden==0||startNameList.length!=0?  MyColors.themeColor:Colors.black,fontSize: 14.sp),
                      direction: Direction.right,
                      padding: 4,
                      iconWidget:startHidden==1? Icon(Icons.keyboard_arrow_down,color: MyColors.authTipColor,size: 20,):Icon(Icons.keyboard_arrow_up,size: 20,color: MyColors.themeColor,),
                      onTap: () {
                        setState(() {
                          startHidden==1?startHidden=0:startHidden=1;
                          addressType=1;
                          endHidden=1;
                          typeHidden=1;
                          isChooseList=[];
                          selectedProvince = "";
                          selectedCity = "";
                          selectedDistrict = "";
                          currentLevel = "province";
                          isChooseList =startNameList;
                        });

                      }),
                ),
                Container(
                  width: screenSize.width/3,
                  child:   BrnIconButton(
                      name: endNameList.length==1?endNameList.join(','): endNameList.length>1?endNameList[1]+"...":'卸货地',
                      style: TextStyle(color:endHidden==0||endNameList.length!=0?  MyColors.themeColor:Colors.black,fontSize: 14.sp),
                      direction: Direction.right,
                      padding: 4,
                      iconWidget:endHidden==1? Icon(Icons.keyboard_arrow_down,color: MyColors.authTipColor,size: 20,):Icon(Icons.keyboard_arrow_up,size: 20,color: MyColors.themeColor,),
                      onTap: () {
                        setState(() {
                          endHidden==1?endHidden=0:endHidden=1;
                          addressType=2;
                          startHidden=1;
                          typeHidden=1;
                          isChooseList=[];
                          selectedProvince = "";
                          selectedCity = "";
                          selectedDistrict = "";
                          currentLevel = "province";
                          isChooseList =endNameList;
                        });

                      }),
                ),
                Container(
                  width: screenSize.width/3,
                  child:   BrnIconButton(
                      name: '车辆类型',
                      style: TextStyle(color:typeHidden==0?  MyColors.themeColor:Colors.black,fontSize: 14.sp),
                      direction: Direction.right,
                      padding: 4,
                      iconWidget:typeHidden==1? Icon(Icons.keyboard_arrow_down,color: MyColors.authTipColor,size: 20,):Icon(Icons.keyboard_arrow_up,size: 20,color: MyColors.themeColor,),
                      onTap: () {
                       setState(() {
                         typeHidden==0?typeHidden=1:typeHidden=0;
                         startHidden=1;
                         endHidden=1;
                         isChooseList=[];
                         selectedProvince = "";
                         selectedCity = "";
                         selectedDistrict = "";
                         currentLevel = "province";
                         isChooseList =endNameList;
                       });
                      }),
                ),
              ],
            ),
          ),
          startHidden==0||endHidden==0?
          Container(
            padding: EdgeInsets.only(left: 16.w,right: 16.w),
            color: Colors.white,
            child: Column(
              children: [
                Container(
                  height:  screenSize.height-200.h,
                  child:   Column(
                    children: [
                      Expanded(child:    ListView(
                        // crossAxisAlignment: CrossAxisAlignment.start,
                        padding: EdgeInsets.zero,
                        children: [
                          Divider(height: 1.h,color: MyColors.backgreyColor,),
                          SizedBox(height: 10.h,),
                          Text("已选地区("+isChooseList.length.toString()+"/3)",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          SizedBox(height: isChooseList.length==0?0:8.h,),
                          isChooseList.length==0?SizedBox(height: 0,):
                          Padding(
                            padding: const EdgeInsets.all(8.0),
                            child: Wrap(
                              spacing: 8.0, // 两个Container之间的水平间距
                              runSpacing: 10.0, // 行与行之间的垂直间距
                              children: isChooseList.map((length) {
                                bool? isSelected = isChooseList.contains(length);
                                return GestureDetector(
                                  onTap: () {
                                    // 处理点击事件
                                    setState(() {
                                      if (isSelected) {
                                        // 如果已经被选中，则移除
                                        isChooseList.remove(length);
                                        selectedProvince = "";
                                        selectedCity = "";
                                        selectedDistrict = "";
                                        currentLevel = "province";
                                      } else  {
                                        // 如果未被选中且未达到最大选择数量，则添加
                                        // isChooseList.add(length);
                                        // print(isChooseList);
                                      }
                                    });
                                  },
                                  child: Container(
                                    padding: EdgeInsets.only( right: 10.w,left: 10.w,top: 2.h,bottom: 2.h),
                                    constraints: BoxConstraints(
                                      // minWidth: 65.w,
                                      maxWidth:200.w, // 限制文本最大宽度
                                    ), // Container宽度
                                    decoration: BoxDecoration(
                                      border: Border.all(
                                        color: MyColors.themeColor , // 边框颜色
                                        width: 1.0, // 边框宽度
                                      ),
                                      color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                      borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                                    ),
                                    child:Text(
                                      length+" x",
                                      style: TextStyle(
                                        fontSize: 13.sp,
                                        color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                      ),

                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ),
                          // SizedBox(height: 8.h,),
                          // Text("历史地区",style: TextStyle(color: Colors.black),),
                          // SizedBox(height: 8.h,),
                          // Padding(
                          //   padding: const EdgeInsets.all(8.0),
                          //   child: Wrap(
                          //     spacing: 8.0, // 两个Container之间的水平间距
                          //     runSpacing: 10.0, // 行与行之间的垂直间距
                          //     children: historyList.map((length) {
                          //       bool? isSelected = isChooseList.contains(length);
                          //
                          //       return GestureDetector(
                          //         onTap: () {
                          //           // 处理点击事件
                          //           setState(() {
                          //             if (isSelected) {
                          //               //如果已经被选中，则移除
                          //               isChooseList.remove(length);
                          //
                          //             } else if (isChooseList.length < 3) {
                          //               // 如果未被选中且未达到最大选择数量，则添加
                          //               isChooseList.add(length);
                          //               // print(isChooseList);
                          //             }
                          //           });
                          //         },
                          //         child: Container(
                          //           width: 70.0, // Container宽度
                          //           height: 30.0, // Container高度，使其成为正方形
                          //           decoration: BoxDecoration(
                          //             border: Border.all(
                          //               color: isSelected ?MyColors.themeColor:MyColors.backgreyColor , // 边框颜色
                          //               width: 1.0, // 边框宽度
                          //             ),
                          //             color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                          //             borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                          //           ),
                          //           child: Center(
                          //             child: Text(
                          //               length,
                          //               style: TextStyle(
                          //                 fontSize: 13.sp,
                          //                 color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                          //               ),
                          //             ),
                          //           ),
                          //         ),
                          //       );
                          //     }).toList(),
                          //   ),
                          // ),
                          //
                          // SizedBox(height: 10),

                          SizedBox(height: 8.h,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Row(
                                children: [
                                  selectedProvince!=""? Text(selectedProvince,style: TextStyle(color: Colors.black,fontSize: 14.sp),)
                                      : Text(selectedProvince!=""?selectedProvince:"全国",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                  Text(" >",style: TextStyle(color: Colors.black),),
                                  Text(selectedCity!=""&&selectedCity!="全省"?selectedCity :"请选择市",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                  if(selectedCity!=""&&selectedDistrict==""&&selectedCity!="全省")
                                    Row(
                                      children: [
                                        Text(" >",style: TextStyle(color: Colors.black),),
                                        Text("请选择区",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                      ],
                                    ),
                                  if(selectedDistrict!=""&&selectedCity!="全市")
                                    Row(
                                      children: [
                                        Text(" >",style: TextStyle(color: Colors.black),),
                                        Text(selectedDistrict,style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                      ],
                                    )
                                ],
                              ),
                              if (currentLevel!="province")
                                GestureDetector(
                                  child: Text("返回上一级",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),),
                                  onTap: (){
                                    setState(() {
                                      if(currentLevel == "city")

                                        currentLevel = "province";
                                      if(currentLevel == "district")
                                        currentLevel = "city";
                                    });
                                  },
                                )
                            ],
                          ),
                          SizedBox(height: 8.h,),
                          Container(
                            height: screenSize.height/2.2,
                            child: ListView(
                              children: [
                                if (currentLevel == "province")
                                  buildButtonRow("省", getItems(getProvinces()), (value) {
                                    setState(() {
                                      selectedProvince = value;
                                      selectedCity = "";
                                      selectedDistrict = "";
                                      currentLevel = "city";
                                      updateSelectedAreas();
                                    });
                                  }),

// 在 _MyHomePageState 类的 build 方法中，如果当前级别为 "city"，则显示市的按钮行
                                if (currentLevel == "city")
                                  buildButtonRow("市", getItems(getCities(selectedProvince)), (value) {
                                    setState(() {
                                      selectedCity = value;
                                      selectedDistrict = "";
                                      currentLevel = "district";
                                      updateSelectedAreas();
                                    });
                                  }),
                                if (currentLevel == "district"&&selectedCity =="全省")
                                  buildButtonRow("市", getItems(getCities(selectedProvince)), (value) {
                                    setState(() {
                                      selectedCity = value;
                                      selectedDistrict = "";
                                      currentLevel = "district";
                                      updateSelectedAreas();
                                    });
                                  }),
// 在 _MyHomePageState 类的 build 方法中，如果当前级别为 "district"，则显示区的按钮行
                                if (currentLevel == "district"&&selectedCity !="全省")
                                  buildButtonRow("区", getItems(getDistricts(selectedProvince, selectedCity)), (value) {
                                    setState(() {
                                      selectedDistrict = value;
                                      updateSelectedAreas();
                                    });
                                  }),
                              ],
                            ),
                          ),


                          SizedBox(height: 30.h,),

                        ],
                      ),
                      ),
                      Container(
                        padding: EdgeInsets.only(bottom: 5.h),
                        child:    Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            BrnSmallOutlineButton(
                              title: '重置',
                              radius: 30,
                              width: 120.w,
                              textColor: MyColors.themeColor,
                              lineColor: MyColors.themeColor,
                              onTap: () {
                                setState(() {
                                  isChooseList=[];
                                  setState(() {
                                    selectedProvince = "";
                                    selectedCity = "";
                                    selectedDistrict = "";
                                    currentLevel = "province"; // 重置为省级别
                                    startNameList=[];
                                    endNameList=[];
                                  });
                                });
                              },
                            ),
                            SizedBox(width: 20.w,),
                            BrnSmallMainButton(
                              title: '确定',
                              radius: 30,
                              width: 120.w,
                              bgColor: MyColors.themeColor,
                              textColor: Colors.white,
                              onTap: () {
                                setState(() {

                                  if (startHidden!=1){
                                    startCodeList=[];
                                    startNameList=[];
                                    List result =[];
                                    for (String item in isChooseList) {
                                      if (item.contains("市")) {
                                        result.add({"province": "", "city": item, "county": ""});
                                      } else if (item.contains("区")||item.contains("县")) {
                                        result.add({"province": "", "city": "", "county": item});
                                      } else {
                                        result.add({"province": item, "city": "", "county": ""});
                                      }
                                      startNameList.add(item);
                                    }
                                    chooseStartList=result;
                                  }else if (endHidden!=1){
                                    endCodeList=[];
                                    endNameList=[];
                                    List result =[];
                                    for (String item in isChooseList) {
                                      if (item.contains("市")) {
                                        result.add({"province": "", "city": item, "county": ""});
                                      } else if (item.contains("区")||item.contains("县")) {
                                        result.add({"province": "", "city": "", "county": item});
                                      } else {
                                        result.add({"province": item, "city": "", "county": ""});
                                      }
                                      endNameList.add(item);
                                    }
                                    chooseEndList=result;
                                  }
                                  if(startHidden==0) {
                                    for (String cityName in startNameList) {
                                      String cityCode = getCityCodeByName(
                                          MyCityListData.CityList, cityName);
                                      if (cityCode != "") {
                                        print('$cityName 的城市编码为：$cityCode');
                                        // cityCode = getCodeResult(cityCode);
                                        startCodeList.add(cityCode);
                                      } else {
                                        print('未找到城市 $cityName');
                                      }
                                    }
                                  }
                                  if(endHidden==0) {
                                    for (String cityName in endNameList) {
                                      String cityCode = getCityCodeByName(
                                          MyCityListData.CityList, cityName);
                                      if (cityCode != "") {
                                        print('$cityName 的城市编码为：$cityCode');
                                        // cityCode = getCodeResult(cityCode);
                                        endCodeList.add(cityCode);
                                      } else {
                                        print('未找到城市 $cityName');
                                      }
                                    }
                                  }
                                  startHidden=1;
                                  endHidden=1;
                                  getNewEmptyCarListAction();
                                });
                              },
                            )
                          ],
                        ),
                      )

                    ],
                  ),

                ),
              ],
            ),
          )
          :typeHidden==0? Container(
            height: screenSize.height-200.h,
            color: Colors.white,
            padding: EdgeInsets.only(left: 16.w,right: 16.w),
            child: Column(
              children: [
                Expanded(child: ListView(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Divider(height: 10.h,color: MyColors.backgreyColor,),
                      Row(
                        children: [
                          Text("车长",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                          Text("（可多选）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Column(
                        children: [
                          Container(
                            height: screenSize.height/5,
                            child: ListView(
                              children: [
                                Wrap(
                                  spacing: 8.w, // 两个Container之间的水平间距
                                  runSpacing: 4.h, // 行与行之间的垂直间距
                                  children: lengthList.map((length) {
                                    bool isSelected = chooseLengthList.contains(length)?? false;
                                    return GestureDetector(
                                      onTap: () {
                                        // 处理点击事件
                                        setState(() {
                                          if (isSelected) {
                                            // 如果已经被选中，则移除
                                            chooseLengthList.remove(length);
                                          } else {
                                            // 如果未被选中且未达到最大选择数量，则添加
                                            chooseLengthList.add(length);
                                          }
                                        });
                                      },
                                      child: Container(
                                        width: 60.w, // Container宽度
                                        height: 25.h, // Container高度，使其成为正方形
                                        decoration: BoxDecoration(
                                          color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                          borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                                        ),
                                        child: Center(
                                          child: Text(
                                            length,
                                            style: TextStyle(
                                              fontSize: 14.sp,
                                              color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                            ),
                                          ),
                                        ),
                                      ),
                                    );
                                  }).toList(),
                                ),
                              ],
                            ),
                          ),

                          SizedBox(height: 4.h,),
                          Row(
                            children: [
                              Text("其他车长",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                              SizedBox(width: 20.w,),
                              Container(
                                width: 200.w,
                                height: 30.h,
                                color: MyColors.backgreyColor,
                                child:  TextField(
                                  decoration: InputDecoration(
                                    hintText: '请输入其他车长',
                                    hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                                    filled: true,
                                    fillColor: MyColors.backgreyColor,
                                    border: InputBorder.none,
                                    alignLabelWithHint: true,
                                    // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                                  ),
                                  keyboardType: TextInputType.number,
                                  textAlign: TextAlign.left,
                                  style: TextStyle(color: Colors.black,fontSize: 13.sp),
                                  onChanged: (value) {
                                    setState(() {
                                      chooseLengthList.add(value+"米");

                                    });
                                  },
                                ),
                              ),
                              Container(
                                width:20.w,
                                height: 20.h,
                                color: MyColors.backgreyColor,
                                child: Center(
                                  child: Text("米",style: TextStyle(fontSize: 13.sp,color: Colors.black),),
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                      SizedBox(height: 4.h,),
                      Row(
                        children: [
                          Text("车型",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                          Text("（可多选）",style: TextStyle(color: MyColors.textColor,fontSize: 14.sp),),
                        ],
                      ),
                      SizedBox(height: 10.h,),
                      Container(
                        height:screenSize.height/6,
                        // padding: EdgeInsets.only(left: 20.w),
                        child:
                        ListView(
                          children: [
                            Wrap(
                              spacing: 8.w, // 两个Container之间的水平间距
                              runSpacing: 4.h, // 行与行之间的垂直间距
                              children: carTypeList.map((length) {
                                bool isSelected = chooseCarTypeList.contains(length)??false;
                                return GestureDetector(
                                  onTap: () {
                                    // 处理点击事件
                                    setState(() {
                                      if (isSelected) {
                                        // 如果已经被选中，则移除
                                        chooseCarTypeList.remove(length);
                                      } else  {
                                        // 如果未被选中且未达到最大选择数量，则添加
                                        chooseCarTypeList.add(length);
                                        print(chooseCarTypeList);
                                      }
                                    });
                                  },
                                  child: Container(
                                    width: 60.w, // Container宽度
                                    height: 25.h, // Container高度，使其成为正方形
                                    decoration: BoxDecoration(
                                      color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                      borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                                    ),
                                    child: Center(
                                      child: Text(
                                        length,
                                        style: TextStyle(
                                          fontSize: 14.sp,
                                          color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              }).toList(),
                            ),
                          ],
                        ),
                      ),

                      SizedBox(height: 15.h,),
                      Row(
                        children: [
                          Text("司机",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                        ],
                      ),
                      SizedBox(height: 6.h,),
                      Container(
                        padding: EdgeInsets.only(left: 20.w),
                        child:  Wrap(
                          spacing: 8.0, // 两个Container之间的水平间距
                          runSpacing: 10.0, // 行与行之间的垂直间距
                          children: driverTypeList.map((length) {
                            bool isSelected = chooseTypeList.contains(length)??false;
                            return GestureDetector(
                              onTap: () {
                                // 处理点击事件
                                setState(() {
                                  if (isSelected) {
                                    // 如果已经被选中，则移除
                                    chooseTypeList.remove(length);
                                  } else  {
                                    // 如果未被选中且未达到最大选择数量，则添加
                                    chooseTypeList.add(length);
                                    print(chooseTypeList);
                                  }
                                });
                              },
                              child: Container(
                                width: 80.0, // Container宽度
                                height: 30.0, // Container高度，使其成为正方形
                                decoration: BoxDecoration(
                                  color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                                  borderRadius: BorderRadius.circular(3.0), // 设置Container的圆角
                                ),
                                child: Center(
                                  child: Text(
                                    length,
                                    style: TextStyle(
                                      fontSize: 14.sp,
                                      color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                    ),
                                  ),
                                ),
                              ),
                            );
                          }).toList(),
                        ),
                      ),

                      // SizedBox(height: 30.h,),


                    ]
                ),
                ),
                Container(
                  padding: EdgeInsets.only(bottom: 5.h),
                  child:  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      BrnSmallOutlineButton(
                        title: '重置',
                        radius: 30,
                        width: 120.w,
                        textColor: MyColors.themeColor,
                        lineColor: MyColors.themeColor,
                        onTap: () {
                          setState(() {
                            chooseLengthList=[];
                            chooseCarTypeList=[];
                            chooseTypeList=[];
                          });
                        },
                      ),
                      SizedBox(width: 20.w,),
                      BrnSmallMainButton(
                        title: '确定',
                        radius: 30,
                        width: 120.w,
                        bgColor: MyColors.themeColor,
                        textColor: Colors.white,
                        onTap: () {
                          setState(() {
                            startHidden=1;
                            endHidden=1;
                            typeHidden=1;
                            if(chooseTypeList.contains("三证齐全"))  cardTypeList.add("3");
                            if(chooseTypeList.contains("五证齐全"))  cardTypeList.add("5");
                            getNewEmptyCarListAction();
                          });

                        },
                      )
                    ],
                  ),
                  margin: EdgeInsets.only(top: 5.h),
                )

              ],
            )

    )
          :
          Container(
            height: screenSize.height-100.h,
            margin: EdgeInsets.only(top: 13.h,left: 10.w,right: 10.w),
            child: EasyRefresh(
              header: ClassicHeader(
                dragText: '下拉刷新',
                armedText: '准备释放',
                readyText: '加载中...',
                processingText: '加载中...',
                processedText: '刷新成功',
                noMoreText: '暂无更多',
                failedText: '刷新失败',
                messageText: '刷新时间 %T',
              ),
                footer: ClassicFooter(
                  dragText: '加载更多',
                  armedText: '准备释放',
                  readyText: '加载中...',
                  processingText: '加载中...',
                  processedText: '加载成功',
                  noMoreText: '暂无更多',
                  failedText: '加载失败',
                  messageText: '加载时间 %T',
                ),
                onRefresh: _onRefresh,
                onLoad: dataList.length > 20*pageNum-1?_onLoadfresh:null,
                child:
          ListView(
            children: [
            dataList.length==0?
             Container(
                height: screenSize.height-180.h,
                child: Center(
                  child: BrnAbnormalStateWidget(
                    img: Image.asset(
                      'lib/Images/OrderList/发货中暂无货源.png',
                      scale: 3.0,
                    ),
                    content: '暂无车源',
                  ),
                ),
              )
              :
                Container(
                  height: screenSize.height-210.h,
                  child: ListView.builder(
                    itemCount:dataList.length,
                    itemBuilder: (context, index) {
                      return GestureDetector(
                        child:Container(
                          padding: EdgeInsets.only(left: 8.w,top: 8.h,right: 8.w,bottom: 8.h),
                          margin: EdgeInsets.only(bottom: 8.h),
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.all(Radius.circular(10))),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Row(
                                    children: [
                                      Text(dataList[index]['loadPlace']['province']+" "+dataList[index]['loadPlace']['city'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                                      Image.asset("lib/Images/OrderList/找货地点指向标.png",width: 22.w,height: 22.h,),
                                      Text(dataList[index]['unloadPlace']['province']+" "+dataList[index]['unloadPlace']['city'],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                                    ],
                                  ),

                                ],
                              ),
                              Text("创建时间:"+dataList[index]['createTime'],style: TextStyle(fontSize: 12.sp,color: MyColors.textColor),),

                              Row(

                                children: [
                                  Image.asset("lib/Images/OrderList/去指派熟车icon.png",width: 20.w,height: 20.h,),
                                  SizedBox(width: 6.w,),
                                  Text(dataList[index]['loadTime'].substring(5, dataList[index]['loadTime'].length - 6).toString()+"点 至 "+dataList[index]['unloadTime'].substring(5, dataList[index]['unloadTime'].length - 6).toString()+"点",style: TextStyle(color: MyColors.themeColor,fontSize: 13.sp),),
                                ]
                              ),
                              SizedBox(height: 4.h,),
                              Row(
                                children: [
                                  Container(
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(10))),
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.all(Radius.circular(10)),
                                      child: dataList[index]['avatarPath']!=""&&dataList[index]['avatarPath']!=null?Image.network(
                                        MyServiceUrl.imgHeader + dataList[index]['avatarPath'],
                                        width: 36.w,
                                        height: 36.h,
                                        fit: BoxFit.cover,
                                      ):Image.asset("lib/Images/login/默认头像.jpeg",width: 36.w, height: 36.h, fit: BoxFit.cover,),
                                    ),
                                  ),
                                  SizedBox(width: 8.w,),
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Text(dataList[index]['realName'],style: TextStyle(color: Colors.black,fontSize: 13.sp),),
                                          SizedBox(width: 6.w,),
                                          // BrnTagCustom.buildBorderTag(
                                          //   tagText: dataList[index]['qualificationCertificateStatus:']!=2?'三证齐全':"五证齐全",
                                          //   textColor: MyColors.themeColor,
                                          //   borderColor: MyColors.themeColor,
                                          //   borderWidth: 1,
                                          //   fontSize: 11.sp,
                                          //   textPadding: EdgeInsets.only(left: 2.w,right: 2.w),
                                          // ),
                                        ],
                                      ),
                                      SizedBox(height: 6.h,),
                                      Row(
                                        children: [
                                          BrnTagCustom(
                                            textColor: Colors.black,
                                            backgroundColor: Color.fromRGBO(239, 239, 239, 1),
                                            fontSize: 10.sp,
                                            textPadding:EdgeInsets.only(left: 8.w,right: 8.w),
                                            tagText: dataList[index]['vehicleLength']!=null?dataList[index]['vehicleLength'].toString()+"米":"--米",
                                          ),
                                          SizedBox(width: 7.w,),
                                          BrnTagCustom(
                                            textPadding:EdgeInsets.only(left: 8.w,right: 8.w),
                                            textColor: Colors.black,
                                            backgroundColor: Color.fromRGBO(239, 239, 239, 1),
                                            fontSize: 10.sp,
                                            tagText: dataList[index]['vehicleModel']!=null?dataList[index]['vehicleModel'].toString():"--",
                                          ),
                                          SizedBox(width: 7.w,),
                                          BrnTagCustom(
                                            textPadding:EdgeInsets.only(left: 8.w,right: 8.w),
                                            textColor: Colors.black,
                                            backgroundColor: Color.fromRGBO(239, 239, 239, 1),
                                            fontSize: 10.sp,
                                            tagText:dataList[index]['vehicleTonnage']!=null? dataList[index]['vehicleTonnage'].toString()+"吨":"--吨",
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),

                                ],
                              ),
                              Divider(height: 10.h,color: MyColors.backgreyColor,),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Column(
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        children: [
                                          Text("好评率:",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                          Text(dataList[index]['rating']+"%",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                        ],
                                      ),
                                      Row(
                                        children: [
                                          Text("信用等级:",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                          Row(
                                            children: List.generate( (divideAndRound(dataList[index]['rating'].toString(), 20)), (starIndex) {
                                              return Icon(Icons.star, color: MyColors.themeColor, size: 20.0);
                                            }),
                                          ),
                                        ],
                                      ),



                                      SizedBox(height: 4.h,),
                                      // Text("交易："+dataList[index]['driverNum'].toString()+"  "+"好评率："+dataList[index]['driverReview'].toString()+"%",style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                                    ],
                                  ),
                                  Container(
                                    height:30.h,
                                    child:  Row(
                                      children: [
                                        GestureDetector(
                                          child:  BrnTagCustom.buildBorderTag(
                                            tagText: '立即派单',
                                            textColor: MyColors.themeColor,
                                            borderColor: MyColors.themeColor,
                                            fontWeight: FontWeight.w600,
                                            borderWidth: 1,
                                            fontSize: 13.sp,
                                            tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                            textPadding: EdgeInsets.all(6),
                                          ),
                                          onTap: (){
                                            Navigator.push( context, FadeRoute(page:SelectSourceOfGoods(carMap:dataList[index],)));
                                          },
                                        ),
                                        
                                        SizedBox(width: 8.w,),
                                        GestureDetector(
                                          child:  BrnTagCustom.buildBorderTag(
                                            tagText: '电话联系',
                                            textColor: MyColors.themeColor,
                                            borderColor: MyColors.themeColor,
                                            fontWeight: FontWeight.w600,
                                            borderWidth: 1,
                                            fontSize: 13.sp,
                                            tagBorderRadius:BorderRadius.all(Radius.circular(30)),
                                            textPadding: EdgeInsets.all(6),
                                          ),
                                          onTap: (){
                                            _makePhoneCall(dataList[index]['contactPhone']);
                                          },
                                        ),

                                      ],
                                    ),
                                  )

                                ],
                              )

                            ],
                          ),
                        ),
                        onTap: (){
                          Navigator.push( context, FadeRoute(page:VehicleSourceDetails(dataMap: dataList[index],)));
                        },
                      );

                    },
                  ),
                )

            ],
          )
          ),

          ),
              ],
            ),


    );
  }
  void updateSelectedAreas() {
    if(isChooseList.length<4) {
      if (selectedDistrict.isNotEmpty) {
        isChooseList.add(selectedDistrict);
        isChooseList.remove(selectedProvince);
        isChooseList.remove(selectedCity);
      } else if (selectedCity.isNotEmpty && selectedDistrict.isEmpty) {
        isChooseList.remove(selectedProvince);
        isChooseList.add(selectedCity);
      } else if (selectedProvince.isNotEmpty && selectedDistrict.isEmpty &&
          selectedCity.isEmpty) {
        isChooseList.add(selectedProvince);
      }
      if (isChooseList.length==4)
        isChooseList.remove(isChooseList[3]);
      isChooseList= LinkedHashSet<String>.from(isChooseList).toList();
    }
  }
  List<String> getProvinces() {
    return MyCityListData.CityList.map((province) => getProvinceName(province)).toList();
  }

  List<String> getCities(String province) {
    for (var item in MyCityListData.CityList) {
      if (getProvinceName(item) == province) {
        List<Map<String, dynamic>> cities = item["children"];
        return ['全省', ...cities.map((city) => getCityName(city)).toList()];
      }
    }
    return [];
  }

  List<String> getDistricts(String province, String city) {
    if (city == '全省') {
      List<String> districts = [];
      for (var item in MyCityListData.CityList) {
        if (getProvinceName(item) == province) {
          for (var child in item["children"]) {
            districts.addAll(child["children"].map<String>((district) => getCityName(district)).toList());
          }
        }
      }
      return districts;
    }

    for (var item in MyCityListData.CityList) {
      if (getProvinceName(item) == province) {
        for (var child in item["children"]) {
          if (getCityName(child) == city) {
            return ['全市', ...child["children"].map<String>((district) => getCityName(district)).toList()];
          }
        }
      }
    }
    return [];
  }

  List<String> getItems(List<String> items) {
    items.remove('全省');
    items.remove('全市');
    if (items.isEmpty) {
      return items;
    }
    return items;
  }

  String getProvinceName(Map<String, dynamic> province) {
    return province["cityShortName"] ?? '未知';
  }

  String getCityName(Map<String, dynamic> city) {
    return city["cityName"] ?? '未知';
  }

  Widget buildButtonRow(String label, List<String> items, Function(String) onPressed) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        Text(label, style: TextStyle(fontSize: 18)),
        SizedBox(height: 8),
        Wrap(
          spacing: 8.w,
          runSpacing: 4.h,
          children: items.map((item) => Container(
            width: 74.w,
            child: InkWell(
              onTap: () => onPressed(item),
              child: Container(
                padding: EdgeInsets.all(8.0),
                decoration: BoxDecoration(
                  color: item == getSelectedItem() ||item =="全省"? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor,
                  borderRadius: BorderRadius.circular(5.0),
                ),
                child: Center(
                  child: Text(
                    item,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: item == getSelectedItem() ? MyColors.themeColor : Colors.black,
                    ),
                  ),
                ),
              ),
            ),
          )).toList(),
        ),
      ],
    );
  }

  String getSelectedItem() {
    switch (currentLevel) {
      case "province":
        return selectedProvince;
      case "city":
        return selectedCity;
      case "district":
        return selectedDistrict;
      default:
        return '';
    }
  }
}
